<template>
  <a-modal
    class="common-modal"
    :title="title"
    :footer="null"
    :width="560"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :maskClosable="false"
    style="top: 5%"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :model="formState" @validateFields="handleOk" ref="formRef" layout="vertical" class="common-modal-content">
        <a-row > 
          <a-col :span="24">
            <a-form-item :label="$t('basicData.name')" name="nickName" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true, message: $t('sysManage.enterName') }]">
              <a-input v-model:value.trim="formState.nickName" :placeholder="$t('common.pleaseInput')" />
            </a-form-item>
          </a-col> 
          <a-col :span="24">
            <a-form-item :label="$t('deviceManage.waterLine')" name="lineIdAry" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true, message: $t('video.pleaseSelectWaterLine') }]">
              <a-select v-model:value="formState.lineIdAry" allowClear :placeholder="$t('common.pleaseSelect')" mode="multiple">
                <a-select-option v-for="(item,key) in selectOptions.waterList" :key="key" :value="item.id">{{item.lineNo}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('basicData.jobNo')" name="staffNo" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true, message: $t('sysManage.enterJobNo') }]">
              <a-input v-model:value.trim="formState.staffNo" :placeholder="$t('common.pleaseInput')" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('sysManage.phoneNo')" name="phonenumber" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: false, message: $t('sysManage.enterPhoneNo') },{ pattern: /^1\d{10}$/, message: $t('other.pleaseEnterTheCorrectFormatPhoneNumber'),trigger: 'change' }]" :extra="$t('other.mobileTerminalAppletLoginRequired')">
              <a-input v-model:value.trim="formState.phonenumber" :placeholder="$t('common.pleaseInput')" />
              <!-- <span style="color: #33333342;">移动端（小程序）登录必填</span> -->
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('sysManage.depart')" name="deptId" :labelCol="labelCol" :wrapperCol="wrapperCol" >
              <!--<a-select v-model:value="formState.deptId" allowClear  :placeholder="$t('common.pleaseSelect')">-->
                <a-tree-select show-search style="width:100%;" :dropdown-style="{ maxHeight: '500px', overflow: 'auto' }" :placeholder="$t('common.pleaseSelect')" allowClear tree-default-expand-all :tree-data="selectOptions.departList" :field-names="fieldNames" v-model:value="formState.deptId"></a-tree-select>
                <!--<a-select-option v-for="(item,key) in selectOptions.departList" :key="key" :value="item.id">{{item.label}}</a-select-option>-->
              <!--</a-select>-->
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('deviceManage.role')" name="roleIdList" :labelCol="labelCol" :wrapperCol="wrapperCol" >
              <a-select v-model:value="formState.roleIdList" allowClear :placeholder="$t('common.pleaseSelect')" mode="multiple">
                <a-select-option v-for="(item,key) in selectOptions.roleList" :key="key" :value="item.id">{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('common.startState')" name="status" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true, message: $t('sysManage.selectEnable') }]">
              <a-radio-group v-model:value="formState.status">
                <a-radio :value="0">{{$t('common.start')}}</a-radio>
                <a-radio :value="1">{{$t('common.stop')}}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row> 
      </a-form>
      <div class="common-modal-footer">
        <a-button @click="handleCancel" class="cancel">{{
          $t("common.cancel")
        }}</a-button>
        <a-button @click="handleOk" type="primary" class="confirm">{{
          $t("common.ok")
        }}</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script setup name="operateStaff">
import { nextTick, ref } from "vue";
import axios from "@/utils/request";
import { cloneDeep } from "lodash";
import { message } from "ant-design-vue";
import i18n from "@/locales/index";
const { t } = i18n.global;
const emits = defineEmits(['ok'])
const labelCol = { xs: { span: 24 }, sm: { span: 23} }
const wrapperCol = { xs: { span: 24 }, sm: { span: 23 } } 
let title = ref('')
let visible = ref(false)
let isEdit = ref(false)
let confirmLoading = ref(false)
const selectOptions = ref({})
let recordInfo = ref({})
let formState = ref({})
const formRef = ref()
const fieldNames = { children: 'children', label: 'label', value: 'id' }

const open = async (record,editable) => {
  initModalData(record, editable)
  await nextTick()
  if (!record.id) {
    record.status = 0;
  }
  formState.value = cloneDeep(record);
};
const initModalData = (record, editable) => {
  title.value = editable ? t("sysManage.editUser") : t("sysManage.addUser");
  isEdit.value = editable
  visible.value = true
  let roleIdList = []
  if (record.roles) roleIdList = record.roles.map(item=>item.id) 
  record.lineIdAry = record.lineIds ? record.lineIds.split(',') : []
  record.roleIdList  = roleIdList
  recordInfo.value = Object.assign({}, record) 
} 
const queryParams = (value) => {
  const params = cloneDeep(value)
  params.lineIds = value.lineIdAry.join(',')
  params.id = recordInfo.value.id
  delete params.lineIdAry
  return params
}
// 提交表单
const handleOk = async () => {
  try {
    const values = await formRef.value.validateFields();
    let arr = []
    if (values.roleIdList){
      selectOptions.value.roleList.forEach(item=>{
          if( values.roleIdList.includes(item.id)){
            arr.push(item)
          }
        }
      )
    }
    values.roleIds = values.roleIdList
    values.roles = arr 
    const sendUrl = isEdit.value ? '/api/system/user/edit' : '/api/system/user/add'
    confirmLoading.value = true 
    const res = await axios.postAction(sendUrl, queryParams(values)) 
    if (res.success) {
      emits("ok");
      message.success(res.msg || t("common.doSuccess"));
    }
    confirmLoading.value = false; // 刷新
    visible.value = false;
  } catch (err) {
    console.log("0000000", err);
  }
  confirmLoading.value = false
}
const handleCancel = () => {
  visible.value = false;
  initModalStatus();
};
const initModalStatus = () => {
  confirmLoading.value = false;
  formState.value = {};
  formRef.value.resetFields();
};
const initSelectOptions = (obj) => {
  selectOptions.value = obj
}
defineExpose({
  open,
  initSelectOptions,
});
</script>
